#!/usr/bin/env bash
set -Eeuo pipefail

# Root-level quick start for Linux/macOS
# Usage: ./start (after chmod +x start) or: bash start

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT_DIR"

echo "[start] Project root: $ROOT_DIR"

# Select Python
PYTHON_BIN="python3"
if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
  PYTHON_BIN="python"
fi

echo "[start] Using Python: $PYTHON_BIN ($("$PYTHON_BIN" -V 2>&1))"

# Create venv if needed
if [ ! -d "venv" ]; then
  echo "[start] Creating virtual environment..."
  "$PYTHON_BIN" -m venv venv
fi

echo "[start] Activating virtual environment..."
# shellcheck disable=SC1091
source "venv/bin/activate"

venv_created=0
if [ ! -d "venv" ]; then
  venv_created=1
fi

if [ "$venv_created" -eq 1 ]; then
  echo "[start] Upgrading pip (first run)..."
  python -m pip install --upgrade --disable-pip-version-check pip wheel >/dev/null 2>&1 || true
fi

# Install deps only when requirements changed
REQ_FILE="requirements.txt"
HASH_FILE="venv/.requirements.sha256"

hash_file() {
  local file="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | awk '{print $1}'
  else
    # Fallback to Python
    "$PYTHON_BIN" - <<'PY'
import hashlib, sys
p=sys.argv[1]
with open(p,'rb') as f:
    h=hashlib.sha256(f.read()).hexdigest()
print(h)
PY
  fi
}

FORCE_INSTALL=0
if [ "${1-}" = "--force-install" ]; then
  FORCE_INSTALL=1
fi

if [ -f "$REQ_FILE" ]; then
  CURR_HASH=$(hash_file "$REQ_FILE")
  OLD_HASH=""
  if [ -f "$HASH_FILE" ]; then
    OLD_HASH=$(cat "$HASH_FILE" 2>/dev/null || true)
  fi
  if [ "$FORCE_INSTALL" -eq 1 ] || [ "$venv_created" -eq 1 ] || [ "$CURR_HASH" != "$OLD_HASH" ]; then
    echo "[start] Installing/updating Python dependencies..."
    # Quiet install; show only summary line
    pip install -r "$REQ_FILE" --disable-pip-version-check -q || pip install -r "$REQ_FILE" --disable-pip-version-check
    mkdir -p "$(dirname "$HASH_FILE")"
    printf "%s" "$CURR_HASH" > "$HASH_FILE"
  else
    echo "[start] Dependencies up to date; skipping install."
  fi
fi

echo "[start] Running app..."
python app.py
